<template>
  <div>
    <!-- 派单完成 2018/3/7 11:44 zhangQ -->

    <Row>
      <i-col span="4">
        <Button type="error" size="large" @click="fleetDispatchDriverRemove">
          撤销派单
        </Button>
      </i-col>
      <i-col span="20">
        <Form ref="subOrderTabParam" label-position="right" inline>
          <FormItem>
            <Input type="text" v-model="SearchContainerNo" placeholder="集装箱号"></Input>
          </FormItem>
          <FormItem>
            <Button type="primary" @click="subSearch" icon="ios-search">
              查询
            </Button>
          </FormItem>
        </Form>
      </i-col>
    </Row>
    <Row>
      <i-col span="24">
        <Table ref="dispatchCompleteTabRef" style="margin-top: 15px;" :columns="subOrderColumn" :data="searchData"
          @on-selection-change="subOrderCheck" height="600" highlight-row
          @on-current-change="onCurrentChange"></Table>
      </i-col>
    </Row>
    <Modal
      v-model="takeOutContainerShow"
      title="填写掏箱个数">
      <Row>
        <label style="width: 80px">
          掏箱个数
        </label>
        <i-input type="text" style="width: 300px" v-model="takeOutContainerNum" placeholder="输入件数">
        </i-input>
        <Button type="info" @click="confrimAddData">确定</Button>
        <Button type="primary" @click="takeOutContainerShow = false">取消</Button>
      </Row>
      <div slot="footer">
      </div>
    </Modal>
  </div>
</template>

<script>
  import {assignmentToDriverRemove, completTakeOutConByFleetId, fleetBindDriverOrder} from '@api/backEnd/fleetOrder'
  import dispatchCompleteExpand from './dispatchCompleteExpand'
  import checkDriverModal from './checkDriverModal'
  import xlinkModal from '@components/modal/xlinkModal'
  import _ from 'lodash'
  import {getTrainTypeCN} from './trainTypeEnum'

  export default {
    name: 'dispatch-complete',
    data () {
      let SearchContainerNo = ''
      let subOrderColumn = [
        {
          title: '操作',
          key: 'action',
          align: 'center',
          width: 250,
          render: (h, params) => {
            let voucherImg = params.row.voucherImg
            let viewImg = (<i-button size="small" style="margin-right: 5px;">图片查看</i-button>)
            if (voucherImg) {
              viewImg = (<i-button type="primary" size="small" style="margin-right: 5px;" onClick={() => this.viewDetailImgAction(params.row)}>图片查看</i-button>)
            }
            let btnArray = []
            let removeBtn1 = (<i-button type="primary" size="small" style="margin-right: 5px;" onClick={() => this.confrimQueryData(params.row)}>掏箱完成</i-button>)
            if (params.row.takeOutContainerState === 1 && !params.row.groupNo) {
              btnArray.push(removeBtn1)
            }
            if (params.row.takeOutContainerState === 0 && !params.row.groupNo) {
              btnArray.push(<i-button type="primary" size="small" style="margin-right: 5px;" onClick={() => this.bindOrderAction(params.row)}>司机绑单</i-button>)
            }
            powerUtil.contains('orderListUnfinishedFleet') && btnArray.push(viewImg)
            return (btnArray)
          }
        },
        {
          type: 'index',
          width: 60
        },
        {
          type: 'expand',
          width: 50,
          render: (h, params) => {
            /* let checkVal = ''
             if (params.row._checked) {
             checkVal = 'All'
             } */
            return h(dispatchCompleteExpand, {
              props: {
                rows: params.row.expand,
                rowsAll: params.row,
                currentRowOneLine: {rowId: params.row.itemIndex}
              },
              on: {
                'reloadData': () => this.reloadDataAll()
              }
            })
          }
        },
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: '掏箱',
          ellipsis: 'false',
          width: 100,
          render: (h, params) => {
            let state = '非掏箱'
            // console.log(params.row.takeOutContainerState)
            if (params.row.takeOutContainerState === 1) {
              state = '掏箱'
            }
            if (params.row.groupNo) {
              state = ''
            }
            return (<span>{state}</span>)
          }
        },
        {
          title: '火车车种类型',
          ellipsis: 'false',
          width: 150,
          render: (h, params) => {
            let trainType = params.row.trainType
            let trainTypeCN = getTrainTypeCN(trainType)
            if (params.row.groupNo) {
              trainTypeCN = '未特定司机子运单'
            }
            return (<span>{trainTypeCN}</span>)
          }
        },
        {
          title: '箱号',
          ellipsis: 'false',
          width: 150,
          key: 'containerNo'
        },
        {
          title: '发货人',
          ellipsis: 'false',
          key: 'receiver',
          width: 250
        },
        {
          title: '收货人',
          ellipsis: 'false',
          key: 'shipper',
          width: 250
        },
        {
          title: '司机',
          ellipsis: 'false',
          key: 'driverId',
          width: 200,
          render: (h, params) => {
            return (<span>{params.row.driverName}</span>)
          }
        },
        {
          title: '送货地址',
          ellipsis: 'false',
          width: 200,
          key: 'outAddress'
        },
        {
          title: '联系人',
          ellipsis: 'false',
          width: 100,
          key: 'outContacts'
        },
        {
          title: '联系人电话',
          ellipsis: 'false',
          width: 150,
          key: 'outMobile'
        },
        {
          title: '品名',
          ellipsis: 'false',
          key: 'pm',
          width: 150
        },
        {
          title: '接取费(元)',
          ellipsis: 'false',
          key: 'receiveFee',
          width: 120
        },
        {
          title: '送达费(元)',
          ellipsis: 'false',
          key: 'deliverFee',
          width: 120
        }
      ]
      let selectionSubOrder = []
      let rebuildData = []
      let currentRow = {}
      let takeOutContainerNum = 0
      let takeOutContainerShow = false
      let dribverParam = {}
      let searchData = []
      let datas = {
        subOrderColumn,
        selectionSubOrder,
        rebuildData,
        currentRow,
        takeOutContainerNum,
        takeOutContainerShow,
        dribverParam,
        SearchContainerNo,
        searchData
      }
      return datas
    },
    props: {
      dispatchCompleteData: {
        type: Array,
        default () {
          return []
        }
      },
      currentMainOrder: {
        type: Object,
        default () {
          return {}
        }
      }
    },
    computed: {},
    watch: {
      'dispatchCompleteData.length' (val, oldval) {
        if (val > 0) {
          this.rebuildMethod()
        } else {
          this.searchData = []
        }
      },
      SearchContainerNo (val) {
        if (!val) {
          this.subSearch()
        }
      }
    },
    methods: {
      /**
       * TODO(给司机绑单)
       * @auther zhangQ
       * @date 2018/8/25 22:16
       */
      bindOrderAction (row) {
        let sendObj = {
          driverId: row.driverId,
          containerNo: row.containerHead + row.containerBody,
          voucherImg: '[]'
        }
        fleetBindDriverOrder(sendObj).then(res => {
          if (+res.data.isSuccess === 1) {
            this.$Notice.success({
              title: '操作成功'
            })
            this.$emit('refreshSource')
          }
        })
      },
      reloadDataAll () {
        this.$emit('refreshSource')
      },
      viewDetailImgAction (row) {
        this.$emit('viewDetailImg', row)
      },
      subOrderCheck (selection) {
        selection.forEach((item) => {
          this.$refs.dispatchCompleteTabRef.data[item.itemIndex]._checked = true
          item._checked = true
        })
        this.selectionSubOrder = selection
      },
      confrimAddData () {
        this.handleTakeOutComplete(this.dribverParam)
        this.takeOutContainerShow = false
      },
      handleTakeOutComplete (rows) {
        console.log('takeOutContainerNum', this.takeOutContainerNum)
        let param = {
          subOrderId: rows.subOrderId,
          fleetOrderId: rows.fleetOrderId,
          takeOutContainerNum: this.takeOutContainerNum
        }
        console.log(param)
        completTakeOutConByFleetId(param).then(res => {
          if (res.data.isSuccess === 1) {
            this.$Message.success('已完成')
            this.reloadDataAll()
            // this.$emit('reloadData')
          } else {
            this.$Message.success(res.data.res)
          }
        })
      },
      confrimQueryData (value) {
        this.takeOutContainerShow = true
        this.dribverParam = value
      },
      fleetDispatchDriverRemove () {
        if (!(this.selectionSubOrder && this.selectionSubOrder.length > 0)) {
          this.$Notice.warning({
            title: '警告',
            desc: '请选择子运单'
          })
          return
        }
        let param = []
        this.selectionSubOrder.forEach((item) => {
          if (!item.groupNo) {
            param.push({
              id: item.id,
              groupNo: item.sendDriverGroupNo
            })
          } else if (item.groupNo) {
            item.expand.forEach((obj) => {
              param.push({
                id: obj.id,
                groupNo: obj.sendDriverGroupNo
              })
            })
          }
        })
        assignmentToDriverRemove(param).then(res => {
          if (+res.data.isSuccess === 1) {
            this.$Message.success('撤销成功')
            this.$emit('refreshSource')
          } else {
            this.$Message.success(res.data.res)
          }
        })
      },
      subSearch () {
        console.log(this.rebuildData)
        if (this.SearchContainerNo) {
          let searchData2 = []
          // console.log(item)
          this.rebuildData.forEach((item) => {
            console.log(item)
            if (item.expand && item.expand.length > 0) {
              let cdpara = {
                groupNo: item.groupNo,
                itemIndex: item.itemIndex,
                shippingAddress: item.shippingAddress,
                _checked: item._checked,
                expand: []
              }
              let zicdpara = []
              let zipd = false
              for (let i = 0; i < item.expand.length; i++) {
                console.log(item.expand[i])
                if (item.expand[i].containerNo.indexOf(this.SearchContainerNo) > 0) { //  === this.SearchContainerNo
                  zicdpara.push(item.expand[i])
                  zipd = true
                }
              }
              if (zipd) {
                cdpara.expand = zicdpara
                searchData2.push(cdpara)
              }
            } else {
              if (item.containerNo.indexOf(this.SearchContainerNo) > 0) { //  === this.SearchContainerNo
                searchData2.push(item)
              }
            }
          })
          this.searchData = searchData2
        } else {
          this.searchData = this.rebuildData
        }
      },
      /**
       * TODO(重新构建数据)
       * @auther zhangQ
       * @date 2018/4/3 16:49
       */
      rebuildMethod () {
        let groupList = _.groupBy(this.dispatchCompleteData, (item) => {
          if (item.sendGroup) {
            return item.sendGroup
          }
          return 'all'
        })
        let rebuildData = []
        let itemIndex = 0
        _.forIn(groupList, function (value, key) {
          console.log(value)
          if (key === 'all') {
            // rebuildData.push(value[0])
            value.forEach((item) => {
              item._disableExpand = true
              item._checked = false
              item.itemIndex = itemIndex
              rebuildData.push(item)
            })
          } else {
            let singleData = {
              groupNo: key,
              shippingAddress: value[0].shippingAddress,
              expand: [],
              itemIndex,
              _checked: false
            }
            value.forEach((item) => {
              singleData.expand.push(item)
            })
            rebuildData.push(singleData)
          }
          itemIndex++
        })
        this.rebuildData = rebuildData
        this.searchData = this.rebuildData
      },
      /**
       * TODO(选择当前行)
       * @auther zhangQ
       * @date 2018/4/3 16:49
       */
      onCurrentChange (currentRow, oldCurrentRow) {
        console.log(this.$refs.dispatchCompleteTabRef)
        currentRow._checked = true
        this.currentRow._checked = true
        if (currentRow.groupNo) {
          this.currentRow = currentRow
        } else {
          this.currentRow = {}
        }
      }
    },
    mounted () {
      this.rebuildMethod()
    },
    components: {dispatchCompleteExpand, checkDriverModal, xlinkModal}
  }
</script>

<style scoped>

</style>
